const app = getApp();
import CryptoJS from 'crypto-js'
function base64_encode(str) {
  var c1, c2, c3;
  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var i = 0, len = str.length, string = ''; 
  while (i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if (i == len) {
      string += base64EncodeChars.charAt(c1 >> 2);
      string += base64EncodeChars.charAt((c1 & 0x3) << 4);
      string += "==";
      break;
    }
    c2 = str.charCodeAt(i++);
    if (i == len) {
      string += base64EncodeChars.charAt(c1 >> 2);
      string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
      string += base64EncodeChars.charAt((c2 & 0xF) << 2);
      string += "=";
      break;
    }
    c3 = str.charCodeAt(i++);
    string += base64EncodeChars.charAt(c1 >> 2);
    string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
    string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
    string += base64EncodeChars.charAt(c3 & 0x3F)
  }
  return string
}
var map = {
  "零": 0,

  "一": 1,
  "壹": 1,

  "二": 2,
  "贰": 2,
  "两": 2,

  "三": 3,
  "叁": 3,

  "四": 4,
  "肆": 4,

  "五": 5,
  "伍": 5,

  "六": 6,
  "陆": 6,

  "七": 7,
  "柒": 7,

  "八": 8,
  "捌": 8,

  "九": 9,
  "玖": 9,

  "十": 10,
  "拾": 10,

  "百": 100,
  "佰": 100,

  "千": 1000,
  "仟": 1000,

  "万": 10000,
  "十万": 100000,
  "百万": 1000000,
  "千万": 10000000,
  "亿": 100000000
};

// 解析失败返回-1，成功返回转换后的数字，不支持负数
function numberDigit(chinese_number) {
  var len = chinese_number.length;
  if (len == 0) return -1;
  if (len == 1) return (map[chinese_number] <= 10) ? map[chinese_number] : -1;
  var summary = 0;
  if (map[chinese_number[0]] == 10) {
      chinese_number = "一" + chinese_number;
      len++;
  }
  if (len >= 3 && map[chinese_number[len - 1]] < 10) {
      var last_second_num = map[chinese_number[len - 2]];
      if (last_second_num == 100 || last_second_num == 1000 || last_second_num == 10000 || last_second_num == 100000000) {
          for (var key in map) {
              if (map[key] == last_second_num / 10) {
                  chinese_number += key;
                  len += key.length;
                  break;
              }
          }
      }
  }
  if (chinese_number.match(/亿/g) && chinese_number.match(/亿/g).length > 1) return -1;
  var splited = chinese_number.split("亿");
  if (splited.length == 2) {
      var rest = splited[1] == "" ? 0 : numberDigit(splited[1]);
      return summary + numberDigit(splited[0]) * 100000000 + rest;
  }
  splited = chinese_number.split("万");
  if (splited.length == 2) {
      var rest = splited[1] == "" ? 0 : numberDigit(splited[1]);
      return summary + numberDigit(splited[0]) * 10000 + rest;
  }
  var i = 0;
  while (i < len) {
      var first_char_num = map[chinese_number[i]];
      var second_char_num = map[chinese_number[i + 1]];
      if (second_char_num > 9)
          summary += first_char_num * second_char_num;
      i++;
      if (i == len)
          summary += first_char_num <= 9 ? first_char_num : 0;
  }
  return summary;
};
let url = 'wss://iat-api.xfyun.cn/v2/iat'
let host = 'iat-api.xfyun.cn'
let apiKey = 'c4ecbeee9dc7790254bb9332fb8dbaa8';
let apiSecret = 'NWNjZGM2MjM0YzU2NzhkYThhODMzYzQ1';
let date = new Date().toGMTString()
let algorithm = 'hmac-sha256'
let headers = 'host date request-line'
let signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2/iat HTTP/1.1`
let signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret)
let signature = CryptoJS.enc.Base64.stringify(signatureSha)
let authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`
let authorization = base64_encode(authorizationOrigin)
url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`
const rm = wx.getRecorderManager();
let wxst; //语音websocket
let status = 0;  // 音频的状态
let iatResult = [] // 识别结果
const isEndNumList=[1,2,3,4,5,6,7,8,9,0,'一','二','三','四','五','六','七','八','九','十','千','万'];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    load_num:1,
    first_ab_str:'', //第一个异常字符串
    shop_content:'', //文本（str）
    shop_list:[], //文本（arr）
    unit_list:[], //单位表
    is_recording:false, //是否正在录音
    is_recordStart:false, //启动录音
    is_focus:false,
    cursor:0,
    num_item_list_h:[],
    isShowError:false, //显示错误信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    wx.onSocketOpen((data) => {
      console.log('服务连接成功')
    })
    wx.onSocketError((err) => {
      console.log('服务连接失败，请重试')
    })
    wx.connectSocket({
      url: url
    })
    wx.onSocketMessage((res) => {
      console.log('收到服务器返回消息')
    });
    rm.onStart(() => {//开始录音时触发
      status = 0;
      iatResult = []
      console.log('录音开始')
    });
    rm.onError((res) => {//错误回调
      console.log('录音错误',res);
    });
    rm.onStop(() => {//结束录音时触发
      console.log('录音结束')
      status = 2;
      wx.hideLoading();
      if (wxst.readyState !== 1) {
        return
      }
      wxst.send({
        data: '{"data":{"status":2,"audio":"","format":"audio/L16;rate=8000","encoding":"raw"}}'
      });
      //   const audio = wx.createInnerAudioContext();
      //   audio.src=res.tempFilePath;
      //   audio.play();
    });
    rm.onFrameRecorded((res) => {//每帧触发
      if (wxst.readyState !== 1) {
        return
      }
      const { frameBuffer } = res
      var int16Arr = new Int8Array(frameBuffer);
      const base64 = wx.arrayBufferToBase64(int16Arr)
      switch (status) {
        case 0:
          status = 1;
          wxst.send({
            data: JSON.stringify({
              "common": { 
                "app_id": "95b6d307" 
              },
              "business": {
                "language": "zh_cn",
                "domain": "iat",
                "accent": "mandarin",
                "dwa": "wpgs",
                "ptt": 1,
                "nunum":1,
                "vad_eos": 4000
              },
              "data": {
                "status": 0,
                "format": "audio/L16;rate=16000",
                "encoding": "raw",
                "audio": base64
              }
            })
          })
          break;
        case 1:
          wxst.send({
            data: JSON.stringify({
              "data": {
                "status": 1,
                "format": "audio/L16;rate=16000",
                "encoding": "raw",
                "audio": base64
              }
            })
          })
          break;
      }
    });
    if(options.type==1){  //录入识别
      wx.setNavigationBarTitle({ 
        title: '录入识别'
      });
    }else if(options.type>=2){  //录入编辑
      wx.setNavigationBarTitle({ 
        title: '录入编辑'
      });
      let init_arr = JSON.parse(wx.getStorageSync('dai'));
      if(init_arr.length>0){
        let shop_content_arr = init_arr.map(function(item) {
          return item.pr_name+item.pr_num+item.error_unit_name_show;  
        });
        let shop_content = shop_content_arr.join('，');
        this.setData({
          shop_content:shop_content
        });
      }else{
        this.setData({
          shop_content:''
        });
      };
      wx.removeStorageSync('dai');
    };
    let dataOrderRepeat={}; //测试订单商品是否已存在
    let goodList=[];
    let daiNormalStorage= wx.getStorageSync('dai_normal');
    if(daiNormalStorage){
      daiNormalStorage= JSON.parse(daiNormalStorage);
      if(daiNormalStorage[options.supplier_id]){ //判断当前供应商是否存有数据
        goodList=daiNormalStorage[options.supplier_id];    
      };
    };
    goodList.forEach(function(item,index){
      let dataOrderRepeatItem=item.pr_name+':'+item.error_unit_name_show
      dataOrderRepeat[dataOrderRepeatItem]=index+1;
    });
    this.setData({
      load_num:0,
      type:options.type,
      order_id:options.order_id,
      supplier_id:options.supplier_id,
      client_id:options.client_id,
      insert_index:options.insert_index,
      phonetype:app.globalData.phonetype,
      dataOrderRepeat:dataOrderRepeat,
      is_store_disable:options.is_store_disable=='true'?true:false
    });
  },
  recordtap(){
    this.setData({
      is_recordStart:true
    });
  },
  record(){
    this.setData({temp:this.data.shop_content});
    wxst = wx.connectSocket({ // 开启websocket连接
      url: url,
      success: ()=> {
        //开始录音
        this.setData({
          is_recordStart:false,
          is_recording:true
        });
        rm.start({
          duration: 1000 * 60,
          sampleRate: 16000,
          numberOfChannels: 1,
          encodeBitRate: 48000,
          format: 'PCM',
          frameSize: 5
        });
      }
    });
    wxst.onOpen(()=> {
      wxst.onMessage((res)=> {
        var data = JSON.parse(res.data);      
        if (data.code != 0) {
          return
        }
        let result=data.data.result;
        let str = "";
        iatResult[result.sn] = result
        if (result.pgs == 'rpl') {
          result.rg.forEach((i) => {
            iatResult[i] = null
          })
        }
        iatResult.forEach((item) => {
          if (item != null) {
            item.ws.forEach((ws) => {
              ws.cw.forEach((cw) => {
                str += cw.w;
              })
            })
          }
        });
        // let shop_content=this.data.shop_content;
        // shop_content=shop_content.slice(0,this.data.cursor)+str+shop_content.slice(this.data.cursor,shop_content.length);
        this.setData({
          shop_content: this.data.temp+str //这个是中间的语音识别结果
        });
        if (data.data.status == 2) {//最终识别结果
          // data.data.status ==2 说明数据全部返回完毕，可以关闭连接，释放资源
          wxst.close();
          return;
        }

      });
      wxst.onClose(()=> {
        console.log('WebSocket 关闭成功');
      });
    });
    wxst.onError((res)=> {
      wx.showToast({
        title: '语音服务异常',
        icon: 'error',
        duration: 2000
      })
    });
  },
  recordEnd(){
    this.setData({
      is_recording:false
    });
    setTimeout(()=>{
      rm.stop();
    },500);
  },
  focus_ck(){
    let is_focus=this.data.is_focus;
    if(!is_focus && this.data.load_num==0 && this.data.shop_content==''){
      this.setData({
        is_focus:!is_focus
      });
    };
  },
  focus_ck2(){
    let is_focus=this.data.is_focus;
    this.setData({
      is_focus:!is_focus
    });
  },
  textarea_focus(e){
    this.setData({
      key_h:e.detail.height,
      is_focus:true
    });
  },
  textarea_blur(e){
    this.setData({
      cursor:e.detail.cursor,   //光标位置
      is_focus:false
    });
  },
  // 文本输入
  shop_contentInput(e){
    let cursor=e.detail.cursor;
    let shop_content=e.detail.value;
    this.setData({
      cursor:cursor,   //光标位置
      shop_content:shop_content,
      shop_list:shop_content==''?[]:this.data.shop_list
    });
  },
  // 清空文本
  clear_shop_but(){
    this.setData({
      cursor:0,
      shop_content:'',
      shop_list:[]
    });
  },
  // 文本生成
  shop_sub(){
    let first_ab_str='';
    let first_ab_obj={};
    let shop_content=this.data.shop_content;
    let shop_list=shop_content.split(/[\n,，。 ]/g);
    let new_shop_list=[];
    let postDataArr=[];  //接口传递数组
    let dataRepeat={}; //测试文本商品是否有重复
    let seq=1; 
    var that = this;
    shop_list.forEach(function(item){
      if(item.trim().length!=0){  //过滤空字符
        if(item.substr(-1)=='儿'){ //去除‘儿’
          item=item.slice(0,-1);
        };
        let postItem={};
        var numArr = item.match(/(\d+\.)?\d+|['一二三四五六七八九十零百千万两']+/g);  //取出字符串中的数和汉字数
        if(item.substr(-2)=='千克' || item.substr(-2)=='kg' || item.substr(-2)=='Kg' || item.substr(-1)=='g'){ 
          let type = 1;
          if(item.substr(-2)=='kg' || item.substr(-2)=='Kg'){
            item=item.slice(0,-2);
            if(item.substr(-2)!='千克'){
              item=item+'千克';
            };
            numArr = item.match(/(\d+\.)?\d+|['一二三四五六七八九十零百千万两']+/g);
          }else if(item.substr(-1)=='g'){
            item=item.slice(0,-1);
            if(item.substr(-2)!='千克'){
              item=item+'克';
            };
            if(item.substr(-2)!='千克'){
              type = 2;
            };
            numArr = item.match(/(\d+\.)?\d+|['一二三四五六七八九十零百千万两']+/g);
          };
          if(type == 1){
            if(numArr[numArr.length-1]=='千'){
              if(numArr.length>1){
                numArr.pop();
              }else{
                let index_end=item.lastIndexOf(numArr[numArr.length-1]); //最后一个数的索引
                item=item.slice(0,index_end)+'1000克';
                numArr = item.match(/(\d+\.)?\d+|['一二三四五六七八九十零百千万两']+/g);
              }
            }else{
              let index_end=item.lastIndexOf(numArr[numArr.length-1]); //最后一个数的索引
              item=item.slice(0,index_end)+numberDigit(numArr[numArr.length-1])+'克';
              numArr = item.match(/(\d+\.)?\d+|['一二三四五六七八九十零百千万两']+/g);
            };
          }
        };
        if(numArr){ //字符串中含数字
          let index_end=item.lastIndexOf(numArr[numArr.length-1]); //最后一个数的索引
          if(index_end>0){
            //判断最后一个字符
            if(item.substr(-1)=='半' || item.substr(-1)=='两'){  //最后一个字符为"半或两"
              if(item.substr(-1)=='半'){
                if(isEndNumList.indexOf(parseInt(item.slice(-2,-1)))!=-1){ //'半'前一位是数字
                  first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'缺少单位'+'，';
                  first_ab_obj[seq-1]='缺少单位';
                }else{
                  if(item.slice(-3,-1)=='千克' || item.slice(-3,-1)=='公斤'){   //单位为库中唯二的复字单位
                    if (/(\d+\.)?\d+/.test(numArr[numArr.length-1])) { 
                      let cur_num=parseFloat(numArr[numArr.length-1])+0.5;
                      postItem['trade_name']=item.slice(0,index_end);
                      postItem['pr_num']= parseFloat((cur_num*1).toFixed(2));
                      postItem['unit_name']=item.slice(-3,-1);
                      item=item.slice(0,index_end)+cur_num+item.slice(-3,-1);
                    }else{ //须汉字转数字
                      let cur_num=parseFloat(numberDigit(numArr[numArr.length-1]))+0.5;
                      postItem['trade_name']=item.slice(0,index_end);
                      postItem['pr_num']=cur_num;
                      postItem['unit_name']=item.slice(-3,-1);
                      item=item.slice(0,index_end)+cur_num+item.slice(-3,-1);
                    };
                  }else{  //单字单位
                    if (/(\d+\.)?\d+/.test(numArr[numArr.length-1])) { 
                      let cur_num=parseFloat(numArr[numArr.length-1])+0.5;
                      postItem['trade_name']=item.slice(0,index_end);
                      postItem['pr_num']= parseFloat((cur_num*1).toFixed(2));
                      postItem['unit_name']=item.slice(-2,-1);
                      item=item.slice(0,index_end)+cur_num+item.slice(-2,-1);
                    }else{ //须汉字转数字
                      if(item.slice(-2,-1)=='两'){  //判断eg:七两半,7两半特殊情况
                        first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'缺少单位'+'，';
                        first_ab_obj[seq-1]='缺少单位';
                      }else{
                        let cur_num=parseFloat(numberDigit(numArr[numArr.length-1]))+0.5;
                        postItem['trade_name']=item.slice(0,index_end);
                        postItem['pr_num']=cur_num;
                        postItem['unit_name']=item.slice(-2,-1);
                        item=item.slice(0,index_end)+cur_num+item.slice(-2,-1);
                      }
                    };
                  }
                }
              }else{
                let regex = /斤(\d|['一二两三四五六七八九']){1}两/g;  //单位为汉字或英文字母
                if (regex.test(item.substr(-3))) {  //*斤*两
                  if(numArr.length<2){
                    first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'缺少数量'+'，';
                    first_ab_obj[seq-1]='缺少数量';
                  }else{
                    item=item.slice(0,-1);  //去掉最后的‘两’
                    let numArr2 = item.match(/(\d+\.)?\d+|['一二三四五六七八九十零百千万两']+/g);
                    let cur_1=numArr2[numArr2.length-2];
                    let cur_2=numArr2[numArr2.length-1];
                    let index_end2=item.lastIndexOf(cur_1); //倒数第二个数的索引
                    if(!/(\d+\.)?\d+/.test(cur_1)){
                      cur_1=numberDigit(cur_1);
                    };
                    if(!/(\d+\.)?\d+/.test(cur_2)){
                      cur_2=numberDigit(cur_2);
                    };
                    let cur_num=(parseFloat(cur_1)+0.1*parseFloat(cur_2)).toFixed(1); 
                    postItem['trade_name']=item.slice(0,index_end2);
                    postItem['pr_num']=cur_num;
                    postItem['unit_name']='斤';
                    item=item.slice(0,index_end2)+cur_num+'斤';   
                  }
                }else{ //*两
                  let cur_1=numArr[numArr.length-2]; //末尾‘两’不是数字
                  let index_end2=item.lastIndexOf(cur_1); //倒数第二个数的索引
                  let cur_num=(0.1*parseFloat(cur_1)).toFixed(1);
                  if (/(\d+\.)?\d+/.test(cur_num)) {
                    postItem['trade_name']=item.slice(0,index_end2);
                    postItem['pr_num']=cur_num;
                    postItem['unit_name']='斤';
                    item=item.slice(0,index_end2)+cur_num+'斤';
                  }else{ //须汉字转数字
                    postItem['trade_name']=item.slice(0,index_end2);
                    postItem['pr_num']=numberDigit(cur_num);
                    postItem['unit_name']='斤';
                    item=item.slice(0,index_end2)+numberDigit(cur_num)+'斤';
                  };
                };
              };
            }else{
              let regex = /[a-zA-Z]|[\u4e00-\u9fa5]+/g;  //单位为汉字或英文字母
              if(regex.test(item.substr(-1))){ //最后一个字符为汉字或字母
                if(item.substr(-2)=='千克' || item.substr(-2)=='公斤'){ //单位为库中唯二的复字单位
                  if (/(\d+\.)?\d+/.test(numArr[numArr.length-1])) {
                    postItem['trade_name']=item.slice(0,index_end);
                    postItem['pr_num']=parseFloat((numArr[numArr.length-1]*1).toFixed(2));
                    postItem['unit_name']=item.substr(-2);
                    item=item.slice(0,index_end)+numArr[numArr.length-1]+item.substr(-2);
                  }else{ //须汉字转数字
                    postItem['trade_name']=item.slice(0,index_end);
                    postItem['pr_num']=numberDigit(numArr[numArr.length-1]);
                    postItem['unit_name']=item.substr(-2);
                    item=item.slice(0,index_end)+numberDigit(numArr[numArr.length-1])+item.substr(-2);
                  };
                }else{   //单字单位
                  if (/(\d+\.)?\d+/.test(numArr[numArr.length-1])) {
                    postItem['trade_name']=item.slice(0,index_end);
                    postItem['pr_num']=parseFloat((numArr[numArr.length-1]*1).toFixed(2));
                    postItem['unit_name']=item.substr(-1);
                    item=item.slice(0,index_end)+numArr[numArr.length-1]+item.substr(-1);
                  }else{ //须汉字转数字
                    postItem['trade_name']=item.slice(0,index_end);
                    postItem['pr_num']=numberDigit(numArr[numArr.length-1]);
                    postItem['unit_name']=item.substr(-1);
                    item=item.slice(0,index_end)+numberDigit(numArr[numArr.length-1])+item.substr(-1);
                  };
                };
              }else{
                first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'缺少单位'+'，';
                first_ab_obj[seq-1]='缺少单位';
              };
            };
          }else{
            first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'缺少名称'+'，';
            first_ab_obj[seq-1]='缺少名称';
          };
        }else{
          let index_ban=item.lastIndexOf('半'); //最后一个'半'字的索引
          if(index_ban==-1 || item.substr(-1)=='半'){  //不含‘半’或‘半’在最后一位   
            first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'缺少数量'+'，';
            first_ab_obj[seq-1]='缺少数量';
          }else{
            if(item.substr(-2)=='千克' || item.substr(-2)=='公斤'){ //单位为库中唯二的复字单位
              postItem['trade_name']=item.slice(0,index_ban);
              postItem['pr_num']=0.5;
              postItem['unit_name']=item.substr(-2);
              item=item.slice(0,index_ban)+0.5+item.substr(-2);
            }else{ //单字单位
              postItem['trade_name']=item.slice(0,index_ban);
              postItem['pr_num']=0.5;
              postItem['unit_name']=item.substr(-1);
              item=item.slice(0,index_ban)+0.5+item.substr(-1);
            };
          }
        };
        let dataRepeatItem=postItem['trade_name']+':'+postItem['unit_name'];
        if(dataRepeat[dataRepeatItem]){
          first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'文本重复'+'，';
          first_ab_obj[seq-1]='文本重复';
        }else if(that.data.dataOrderRepeat[dataRepeatItem]>0){
          if(that.data.type==1){
            first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'订单中已存在'+'，';
            first_ab_obj[seq-1]='订单中已存在';
          }else if(that.data.type==3){
            if(that.data.dataOrderRepeat[dataRepeatItem]!= parseInt(that.data.insert_index)+1){
              first_ab_str+='第'+seq+'个商品'+'"'+item+'"'+'订单中已存在'+'，';
              first_ab_obj[seq-1]='订单中已存在';
            };
          }
        };
        new_shop_list.push(item);
        postDataArr.push(postItem);
        dataRepeat[dataRepeatItem]=true;   
        seq++;
      }
    });
    shop_content=new_shop_list.join('\n');
    first_ab_str=first_ab_str.slice(0,first_ab_str.length-1);
    that.setData({
      shop_content:shop_content,
      shop_list:new_shop_list,
      isShowError:Object.keys(first_ab_obj).length>0?true:false,
      first_ab_str:first_ab_str,
      first_ab_obj:first_ab_obj,
    });
    setTimeout(function () {
      that.setData({
        isShowError:false
      });
    }, 5000)
    var query = wx.createSelectorQuery();
    query.selectAll('.entry_textarea_calc_item').boundingClientRect()
    query.exec(function (res) {
        let sum_h=0;
        let num_item_list_h = Object.values(res[0]).map((v) =>{
          sum_h+=v.height;
          return v.height
        });
        that.setData({
          sum_h:sum_h,
          num_item_list_h:num_item_list_h
        });
    });
    if(Object.keys(first_ab_obj).length==0){
      wx.showModal({
        title: '确定生成?',
        success: function (res) {
          if (res.confirm) {
            if(that.data.is_store_disable){
              let shop_arr = postDataArr.map(function(item) {
                let newitem={};
                newitem.good_id = 0;
                newitem.pr_name = item.trade_name;
                newitem.pr_alias = item.trade_name;
                newitem.pr_num = item.pr_num;
                newitem.true_unit = 0;
                newitem.pr_unit = 0;
                newitem.error_unit_name_show = item.unit_name;
                newitem.unit_price = 0;
                newitem.detail_remark = '';
                return newitem;
              });
              that.deal_with(shop_arr);
            }else{
              wx.showLoading({
                title:'生成中...',
              });
              app.AppHttp('api/Orders/YuYinOrCopyOrderPrview', {
                supplier_id:that.data.supplier_id,
                client_id:that.data.client_id,
                order_id:that.data.order_id,
                postData:JSON.stringify(postDataArr)
              }, function(res) {
                let goodList = res.data.map(function(item) {
                  let newItem={
                    good_id:item.good_id,
                    supplier_id:item.supplier_id,
                    client_id:item.client_id,
                    pr_name:item.pr_name,
                    specs:item.specs,
                    pr_cover:item.pr_cover,
                    pr_num:item.pr_num,
                    pr_unit:item.pr_unit,
                    true_unit:item.true_unit,
                    original_unit:item.original_unit,
                    sub_unit_num:item.sub_unit_num,
                    error_unit_name_show:item.error_unit_name_show,
                    detail_remark:item.detail_remark,
                    unit_price:item.unit_price,
                    is_ku:item.is_ku
                  };
                  return newItem;     
                });
                that.deal_with(goodList);
                wx.hideLoading();       
              });
            };
          }
        }
      });
    }else{
      wx.showLoading({
        title:'文本格式有误',
        duration:500
      })
    };
  },
  // 数据处理
  deal_with(goodList){
    let that = this;
    if(goodList.length>0){
      let daiNormalStorage= JSON.parse(wx.getStorageSync('dai_normal'));
      if(that.data.type==1){  //末尾添加(录单)
        daiNormalStorage[that.data.supplier_id]=daiNormalStorage[that.data.supplier_id].concat(goodList);
      }else if(that.data.type==2){  //覆盖(录入编辑)
        daiNormalStorage[that.data.supplier_id]=goodList;
      }else if(that.data.type==3){  //中间插入商品(替换中的编辑)
        let insert_index = parseInt(that.data.insert_index);
        let part_start=daiNormalStorage[that.data.supplier_id].slice(0,insert_index);
        let part_end=daiNormalStorage[that.data.supplier_id].slice(insert_index+1,daiNormalStorage[that.data.supplier_id].length);
        daiNormalStorage[that.data.supplier_id]=[...part_start,...goodList,...part_end];
      };
      wx.setStorageSync('dai_normal',JSON.stringify(daiNormalStorage));
      wx.navigateBack({
        delta:1
      });                    
    };
  },
  // 关闭错误
  close_error_but(){
    this.setData({
      isShowError:false
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    wx.getClipboardData({
      success: function(res){
        wx.hideToast(); //去掉剪贴提示词
        let copy_str=res.data;
        if(copy_str==' '){
          copy_str='';
        };
        if(copy_str){
          let shop_content=that.data.shop_content;
          if(shop_content==''){
            shop_content+=copy_str;       
            wx.setClipboardData({
              data:' ',
              success: function (res) {
                wx.hideToast(); //去掉剪贴提示词
              }
            })
          }else{
            wx.showModal({
              title: '可将以下粘贴至文本',
              content: res.data,
              showCancel: false,
              confirmText:"我知道了",
              success: function (res) {}
            });
          };
          that.setData({
            shop_content:shop_content
          });
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})